<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class AssessmentQuestion extends Model
{
    /**
     * Indicates if the model should be timestamped.
     *
     * @var bool
     */
    public $timestamps = false;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'question_text', 'question_type', 'options', 'scoring_rules', 'is_active'
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'is_active' => 'boolean',
        'created_at' => 'datetime',
    ];

    /**
     * 用户答案关系
     */
    public function userAnswers()
    {
        return $this->hasMany(UserAssessmentAnswer::class, 'question_id');
    }

    /**
     * JSON字段的访问器和修改器
     */
    public function getOptionsAttribute($value)
    {
        return $value ? json_decode($value, true) : [];
    }

    public function setOptionsAttribute($value)
    {
        $this->attributes['options'] = $value ? json_encode($value) : null;
    }

    public function getScoringRulesAttribute($value)
    {
        return $value ? json_decode($value, true) : [];
    }

    public function setScoringRulesAttribute($value)
    {
        $this->attributes['scoring_rules'] = $value ? json_encode($value) : null;
    }

    /**
     * 获取问题类型的中文名称
     */
    public function getTypeNameAttribute()
    {
        $types = [
            'breaking_ice' => '破冰力',
            'empathy' => '共情度',
            'conversation_flow' => '推进技巧'
        ];

        return $types[$this->question_type] ?? '未知类型';
    }

    /**
     * 根据答案计算分数
     */
    public function calculateScore($selectedOption)
    {
        $scoringRules = $this->scoring_rules;
        return $scoringRules[$selectedOption] ?? 0;
    }

    /**
     * 作用域：活跃的问题
     */
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    /**
     * 作用域：按类型筛选
     */
    public function scopeByType($query, $type)
    {
        return $query->where('question_type', $type);
    }
}